package org.ehe.business.overdue.extract;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.ehe.business.monitor.DataExtractor;
import org.ehe.business.monitor.MonitorData;
import org.ehe.business.overdue.domain.OverdueRecord;
import org.ehe.business.overdue.mapper.OverdueRecordMapper;
import org.ehe.business.timeout.contants.BizTypeConstant;
import org.ehe.business.timeout.domain.SsePushMessage;
import org.ehe.business.timeout.mapper.SsePushMessageMapper;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.sse.dto.SseMessageDto;
import org.ehe.common.sse.utils.SseMessageUtils;
import org.ehe.erp.domain.quality.ErpQualityFeedback;
import org.ehe.erp.domain.quality.bo.ErpQualityFeedbackBo;
import org.ehe.erp.domain.quality.vo.ErpQualityFeedbackVo;
import org.ehe.erp.service.quality.ErpQualityFeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
 * 质检管理参数解析
 * @author :zhangnn
 * @className :ProjectDataExtractor
 * @description: TODO
 * @date 2025-10-13 13:56:33
 */
@Slf4j
@Component
public class FeedBackDataExtractor implements DataExtractor {

    @Autowired
    private ErpQualityFeedbackService feedbackService;
    @Autowired
    private ScheduledExecutorService scheduledExecutorService;
    @Autowired
    private SsePushMessageMapper ssePushMessageMapper;
    @Autowired
    private OverdueRecordMapper overdueRecordMapper;

    @Override
    public MonitorData extract(JoinPoint joinPoint, Object result) {

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            log.error("接口无参数，提取失败");
            return null;
        }

        Long bizId = null;
        String status = null;
        ErpQualityFeedbackBo feedbackBo = null;
        boolean isPathVarOnly = false;

        // 场景1：纯路径变量接口（如作废、审核等）
        if (args.length == 1 && args[0] instanceof Long) {
            bizId = (Long) args[0];
            isPathVarOnly = true;
        }
        // 场景2：新增接口
        else if (args.length == 2
            && args[0] instanceof Long
            && args[1] instanceof String) {
            bizId = (Long) args[0];
            isPathVarOnly = true; // 标记为纯路径变量接口
        }
        // 场景3：更新接口（含ErpQualityTaskBo对象）
        else if (args.length == 1 && args[0] instanceof ErpQualityFeedbackBo) {
            feedbackBo = (ErpQualityFeedbackBo) args[0];
            bizId = feedbackBo.getId();
            status = String.valueOf(feedbackBo.getApproveStatus());

        } else if (args.length == 2
            && args[0] instanceof Long
            && args[1] instanceof Long) {
            bizId = (Long) args[0];
            isPathVarOnly = true;
        }
        else if (args.length == 3 && args[0] instanceof Long) {
            bizId = (Long) args[0];
            isPathVarOnly = true;
        } else {
            log.error("未匹配的参数结构，参数类型：{}",
                Arrays.stream(args).map(a -> a.getClass().getName()).collect(Collectors.toList()));
            return null;
        }

        if (bizId == null) {
            log.error("bizId获取失败");
            return null;
        }

        MonitorData data = new MonitorData();
        data.setBizId(bizId);
        data.setStatus(status);

        // 获取反馈详情信息
        if (feedbackBo != null || isPathVarOnly) {
            ErpQualityFeedback feedback = feedbackService.getById(bizId);
            if (feedback == null) {
                log.error("反馈信息不存在，qualityTask's id：{}", bizId);
                return null;
            }
            data.setBizName(feedback.getFeedbackNo());
            data.setCreateBy(feedback.getCreateBy());
            data.setCreateTime(LocalDateTime.now());
            //任务完成需要的天数
            if(null != feedback.getEstimatedHours()){
                data.setDays(Long.valueOf(feedback.getEstimatedHours()));
            }
            //审核状态
            if(StringUtils.isNotBlank(feedback.getApproveStatus())){
                data.setStatus(String.valueOf(feedback.getApproveStatus()));
            }
            data.setTenantId(feedback.getTenantId());
        }

        // 推送逻辑
        ErpQualityFeedbackVo feedback = feedbackService.queryById(bizId);

        List<Long> userIds = new ArrayList<>();
        String engineerName = null;

        String content = "质检反馈：[" + feedback.getFeedbackNo() + "]，"+feedback.getProductName()+"："+feedback.getProblemDesc()+"，反馈人：" + feedback.getFeedbackPerson();
        userIds.add(1L);
        scheduledExecutorService.schedule(() -> {
            SseMessageDto dto = new SseMessageDto();
            dto.setMessage(content);
            dto.setUserIds(userIds);
            SseMessageUtils.publishMessage(dto);
        }, 2, TimeUnit.SECONDS);

        pushMessage(feedback, userIds, content, engineerName);
        return data;
    }

//    private Long getBizIdFromResult(Object result) {
//        if (result instanceof R) {
//            R<?> r = (R<?>) result;
//            Object data = r.getData();
//            if (data == null) {
//                log.error("返回值R中的data为null");
//                return null;
//            }
//            if (data instanceof Long) {
//                return (Long) data;
//            }
//            try {
//                Method getIdMethod = data.getClass().getMethod("getId");
//                Object idObj = getIdMethod.invoke(data);
//                if (idObj instanceof Long) {
//                    return (Long) idObj;
//                } else if (idObj instanceof Integer) {
//                    return ((Integer) idObj).longValue();
//                }
//            } catch (Exception e) {
//                log.error("反射获取id失败", e);
//            }
//        }
//        return null;
//    }

    /**
     * 消息推送
     * @param feedback
     * @param userIds
     * @param content
     * @param engineerName
     */
    private void pushMessage(ErpQualityFeedbackVo feedback, List<Long> userIds, String content, String engineerName) {
        SsePushMessage push = new SsePushMessage();

        OverdueRecord overdueRecord = overdueRecordMapper.selectByBizTypeAndId(
            BizTypeConstant.FEEDBACK + "Overdue", feedback.getId());
        if (Objects.nonNull(overdueRecord)) {
            push.setInstanceId(overdueRecord.getId());
        }
        push.setType("overdue");
        push.setMessage(content);

        if (userIds != null && !userIds.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < userIds.size(); i++) {
                sb.append(userIds.get(i));
                if (i != userIds.size() - 1) {
                    sb.append(",");
                }
            }
            push.setUserIds(sb.toString());
        }
        push.setMessageType(BizTypeConstant.FEEDBACK + "Overdue");
        push.setTenantId(feedback.getTenantId());
        ssePushMessageMapper.insert(push);
    }

    private String getStatusName(String status) {
        if (StringUtils.isBlank(status)) {
            return "";
        }
        switch (status) {
            case "0": return "草稿";
            case "1": return "已提交";
            case "20": return "已通过";
            case "9": return "已拒绝";
            case "6": return "已作废";
            default: return status;
        }
    }
}
